import getInfo
import download
import download2
from getInfo import BSpider
import json
import os
import time
import random


def downloadByUpname():
    Path = ''
    with open("./config.json", 'rb') as f:
        config = json.load(f)
        Path = config['Path']
    # 歌曲保存根目录

    print("浏览器启动中....")
    bilibili = BSpider()
    print("浏览器启动完成")
    # 输入信息
    up_name = input("请输入需要爬取的up主：")
    partition = input("请输入需要爬取的作品分区：(默认音乐区)")
    isSavedetailed = input("是否保存详细数据：(默认false)")
    StartPosition = input("开始位置：(默认1)")
    isVideo = input("是否爬取视频：(默认false)")
    if(StartPosition == ''):
        StartPosition = '1'
    if(partition == ''):
        partition = '音乐'

    # 创建文件夹
    file_path = Path+up_name
    if not os.path.isdir(file_path):
        os.makedirs(file_path)

    # 开始信息爬虫
    bvIdArray = bilibili.get_page(up_name, partition, isSavedetailed)
    bilibili.close_webdriver()
    time.sleep(3)
    bvId = []
    for i in range(0, len(bvIdArray)):
        bvId_moudle = {}
        bvId_moudle['id'] = i+1
        bvId_moudle['bvId'] = bvIdArray[len(bvIdArray)-i-1][31:43]
        bvId.append(bvId_moudle)

    # 保存json
    bvId_empty = []
    start = 1
    if not os.path.exists(file_path+"\\"+"bvId"+".json"):
        with open(file_path+"\\"+"bvId"+".json", 'w+', encoding='utf-8') as f:
            json.dump(bvId_empty, f, ensure_ascii=False,
                      sort_keys=True, indent=4)
        # 如果json文件不存在，创建空json
    with open(file_path+"\\"+"bvId"+".json", 'r') as f:
        bvId_used = json.load(f)
        # 读取bvid.json
    if(bvId.__len__() == len(bvId_used)):
        print("音频已为最新，无需爬取 ^_^")
    else:
        surplus = bvId.__len__() - len(bvId_used)
        Start = str(len(bvIdArray)-surplus+1)
        if(StartPosition == '1'):
            StartPosition = Start
        # 起点更新
        print('json文件生成中 ...')
        with open(file_path+"\\"+"bvId"+".json", 'w+', encoding='utf-8') as f:
            json.dump(bvId, f, ensure_ascii=False, sort_keys=True, indent=4)
        print('json文件已生成')
        # 生成json文件
        # 开始爬虫
        if(isVideo == "true"):
            for i in range(int(StartPosition) - 1, len(bvIdArray)):
                download2.single_download(
                    bvIdArray[len(bvIdArray)-i-1][31:43], file_path)
                print(len(bvIdArray)-i-1)
                time.sleep(random.randint(1, 3))
        else:
            for i in range(int(StartPosition) - 1, len(bvIdArray)):
                download.single_download(
                    bvIdArray[len(bvIdArray)-i-1][31:43], file_path)
                print(len(bvIdArray)-i-1)
                time.sleep(random.randint(1, 3))
